package com.example.ai.config.tools;

import java.util.HashMap;
import java.util.Map;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IpInfoTool {

    @Tool(description = "Get IP information")
    public static String getIpVo(@ToolParam(description = "The IP address to query") String ip) {
        String url = "http://whois.pconline.com.cn/ipJson.jsp?json=true";
        if (StrUtil.isNotBlank(ip)) {
            url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip;
        }
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=UTF-8");
        // 发送 GET 请求
        try (HttpResponse response = HttpRequest.get(url)
                .addHeaders(headers)
                .execute()) {
            // 获取响应体
            String body = response.body();
            JSONObject jsonObj = JSONUtil.parseObj(body);
            log.info("getIpInfo ip:{} body: {}", ip, jsonObj);
            return jsonObj.getStr("addr") + " " + jsonObj.getStr("pro");
        }
    }

}
